package com.luoxiang.socialandroid.fragment;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CHECKSUM;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CURRTIME;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_NONCE;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.adapter.RcCommunityAdapter;
import com.luoxiang.socialandroid.base.LazyLoadFragment;
import com.luoxiang.socialandroid.bean.Dynamic;
import com.luoxiang.socialandroid.bean.DynamicsBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.lib_common.common.Constants;
import com.luoxiang.socialandroid.dialog.LoadingDialog;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils2;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @Description TODO
 * @systemUser Administrator
 * @Author LX
 * @Date 08-29-2022 周一 16:38
 * 社区推荐的fragment
 */
public class CommunityFirstFragment extends LazyLoadFragment {
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private String token;
    private RecyclerView rv_shequ;
    private RcCommunityAdapter adapter;
    private SmartRefreshLayout smartRefreshLayout;
    private int page = 1;//是我们的页数
    private List<Dynamic> dynamicsData = new ArrayList<>();
    private LoadingDialog dialog;


    @Override
    protected int setContentView() {
        return R.layout.fragment_communityfirst;
    }

    public void initView() {
        token = MmkvUtil.INSTANCE.decodeString(Constants.MmkvConst.TOKEN);
        rv_shequ = findViewById(R.id.rv_shequ);
        smartRefreshLayout = findViewById(R.id.smartRefresh);
        smartRefreshLayout.setEnableRefresh(true);
        smartRefreshLayout.setEnableLoadMore(true);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireActivity());
        rv_shequ.setLayoutManager(linearLayoutManager);
        adapter = new RcCommunityAdapter(getActivity());
        rv_shequ.setAdapter(adapter);

        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refreshData(true);
            }
        });
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData(false);
            }
        });
    }

    @Override
    protected void lazyLoad() {
        getDynamics(EXTRA, token, 0, page, 10, "");
    }

    private void refreshData(boolean isMore) {
        if (isMore) {
            page++;
        } else {
            page = 1;
        }
        getRequest();
        getDynamics(EXTRA, token, 0, page, 10, "");
    }

    private void getDynamics(String extra, String token, Integer type, Integer page, Integer limit, String location) {
        NetUtils2.getInstance().getApiService().getDynamics(extra, token, type, page, limit, location)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {

                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoading();
                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        clearLoading();
                        clearLoading();
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStra", decryptStr);
                        Gson gson = new Gson();
                        DynamicsBean molelistBean = gson.fromJson(decryptStr, DynamicsBean.class);

                        if (page == 1) {
                            dynamicsData.clear();
                        }
                        if (molelistBean != null) {
                            if (molelistBean.getData() != null) {
                                dynamicsData.addAll(molelistBean.getData().getDynamics());
                            }
                        }
                        if (molelistBean != null) {
                            adapter.setData(dynamicsData, molelistBean.getData());
                            adapter.notifyDataSetChanged();
                            adapter.setOnAddClickListener(new RcCommunityAdapter.OnAddClickListener() {
                                @Override
                                public void onItemClicks(int position, int dylike) {
                                    getRequest();
                                    String token = MmkvUtil.INSTANCE.decodeString(TOKEN);
                                    getlikeDynamic(EXTRA, token, position, dylike);

                                }
                            });
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                    }

                    @Override
                    public void onComplete() {
                        clearLoading();
                        if (smartRefreshLayout != null) {
                            smartRefreshLayout.finishRefresh();
                            smartRefreshLayout.finishLoadMore();
                        }
                    }
                });
    }


    /**
     * 点赞/取消点赞的方法
     */
    private void getlikeDynamic(String extra, String token, Integer id, Integer like) {
        NetUtils2.getInstance().getApiService().getlikeDynamic(extra, token, id, like)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr", decryptStr);
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 请求头传参方式
     */
    public void getRequest() {
        String apiKey = "17SgH6kkUNk8tyxjR6rbXEDiIR4P3nQh";//prod环境
        String nonce = (int) (Math.random() * 9000 + 1000) + "";//四位随机数
        String currTime = System.currentTimeMillis() + "";//当前时间戳
        String value = apiKey + nonce + currTime;
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("sha1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        messageDigest.update(value.getBytes());
        byte[] bytes = messageDigest.digest();

        //转换成16进制
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        String newCheckSum = buf.toString();
        MmkvUtil.INSTANCE.encode(KEY_NONCE, nonce);
        MmkvUtil.INSTANCE.encode(KEY_CURRTIME, currTime);
        MmkvUtil.INSTANCE.encode(KEY_CHECKSUM, newCheckSum);
    }
}
